/**
 * Creat with IntelliJ IDEA
 * Description:synchronized修饰的方法
 * User:WZW
 * Date:2021-11-28
 * Time:13:46
 */
class Bank implements Runnable{
    int money = 300;
    String treasurerName, cashierName;
    public Bank(String s1,String s2){ treasurerName=s1; cashierName=s2; }
    public void run(){ saveOrTake(30); }
    public synchronized void saveOrTake(int number){
        if(Thread.currentThread().getName().equals(treasurerName)){
            for(int i=1;i<=3;i++){
                money = money + number;
                try { Thread.sleep(1000); }
                catch(InterruptedException e) {}
                System.out.println(treasurerName + " : " + money);
            }
        }
        else if(Thread.currentThread().getName().equals(cashierName)){
            for(int i=1;i<=2;i++){
                money = money-number/2;
                try{ Thread.sleep(1000);}
                catch(InterruptedException e){}
                System.out.println(cashierName + " : " + money);
            }
        }
    }
}

public class Example8_9 {
    public static void main(String args[])
    {
        String treasurerName = "Treaurer", cashierName = "Cashier";
        Bank bank = new Bank(treasurerName,cashierName);

        Thread treasurer, cashier;
        treasurer = new Thread(bank); // 目标对象bank
        cashier = new Thread(bank); // 目标对象bank
        treasurer.setName(treasurerName);
        cashier.setName(cashierName);
        treasurer.start();
        cashier.start();
    }

}
